<script setup>
import { useForm } from '@/components'

defineOptions({
  name: 'DynamicForm'
})

const $props = defineProps({
  schema: { type: Object, required: true },
  formdata: { type: Object },
  submit: { type: Function, required: true },
  loading: { type: Boolean, defaultValue: false },
  submitProp: { type: Object, defaultValue: {} }
})

const { handleSubmit } = useForm()
const onSubmit = handleSubmit((values) => {
  $props.submit(values)
})
</script>
<template>
  <form @submit="onSubmit($event)">
    <div
      class="flex flex-col"
      v-for="{ as, name, label, children, ...attrs } in $props.schema.fields"
      :key="name"
    >
      <label class="font-medium text-lg" :for="name">{{ label }}:</label>
      <Field
        :disabled="$props.loading"
        :as="as"
        :id="name"
        :name="name"
        v-bind="attrs"
        v-model="$props.formdata[name]"
      >
        <template v-if="children && children.length">
          <component
            v-for="({ tag, text, ...childAttrs }, idx) in children"
            :key="idx"
            :is="tag"
            v-bind="childAttrs"
          >
            {{ text }}
          </component>
        </template>
      </Field>
      <small> <ErrorMessage :name="name" class="text-red-500" />&nbsp; </small>
    </div>
    <Button
      class="flex-none"
      size="large"
      type="submit"
      :loading="$props.loading"
      label="Ok"
      v-bind="$props.submitProp"
    />
  </form>
</template>
